package com.xgjweb.fsi.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xgjweb.common.dao.ICommonDao;
import com.xgjweb.common.service.CommonServiceImpl;
import com.xgjweb.common.utils.Constant;
import com.xgjweb.common.utils.XgjWebLogger;
import com.xgjweb.common.utils.XgjWebUtils;
import com.xgjweb.fsi.domain.Album;
import com.xgjweb.fsi.domain.Picture;

public class PictureServiceImpl extends CommonServiceImpl implements
		IPictureService {
	private ICommonDao pictureDao;

	public void setPictureDao(ICommonDao pictureDao) {
		this.pictureDao = pictureDao;
	}

	/**
	 * 添加相片
	 */
	public ActionForward addPicture(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		File newFile = null;
		try {
			request.setCharacterEncoding("UTF-8");
			String path = Constant.ALBUM_PATH;
			RequestContext requestContext = new ServletRequestContext(request);
			// 得到参数
			Integer albumId = Integer.parseInt(parmentByRequest(request,
					"albumId"));
			String name = parmentByRequest(request, "name");
			name = ReEncode(name);
			// 用uuid生成文件名
			String filename = XgjWebUtils.getUUID();
			if (FileUpload.isMultipartContent(requestContext)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置文件最大为1M
				upload.setSizeMax(1024 * 1024);
				List<?> items;
				items = upload.parseRequest(request);
				Iterator<?> it = items.iterator();
				while (it.hasNext()) {
					FileItem fileItem = (FileItem) it.next();
					if (!fileItem.isFormField()) {
						if (fileItem.getName() != null
								&& fileItem.getSize() != 0) {
							Album album = new Album();
							album.setId(albumId);
							album.setStatementName("findAlbum");
							album = (Album) pictureDao.selectByObject(album);
							String albumUrl = album.getUrl();
							// 保存文件到硬盘
							filename = filename + "."
									+ fileItem.getName().split("\\.")[1];
							newFile = new File(path + albumUrl
									+ File.separator + filename);
							String url = albumUrl + "/" + filename;
							// 把文件信息写进数据库
							BufferedImage bufferedImage = ImageIO.read(fileItem
									.getInputStream());
							fileItem.write(newFile);

							Picture picture = new Picture();
							picture.setStatementName("insertPicture");
							picture.setAlbum(album);
							picture.setName(name);
							picture.setUrl(url);
							picture.setHeight(bufferedImage.getHeight());
							picture.setWidth(bufferedImage.getWidth());
							pictureDao.insert(picture);
							// 返回图片名称
							response.getWriter().print(filename);
							response.getWriter().flush();
							response.getWriter().close();
						}
					}

				}
			}
			return null;
		} catch (Exception e) {
			// 发生异常把保存的新图片删除。
			if (newFile != null && newFile.exists()) {
				newFile.delete();
			}
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 删除相片
	 */
	public Boolean deletePicture(Picture picture) throws Exception {
		try {
			File file = new File(Constant.ALBUM_PATH + picture.getUrl());
			if (file.exists()) {
				file.delete();
			}
			picture.setStatementName("deletePicture");
			pictureDao.delete(picture);
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查找相片
	 */
	public Picture findPicture(Picture picture) throws Exception {
		try {
			picture.setStatementName("findPicture");
			picture = (Picture) pictureDao.selectByObject(picture);
			return picture;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查询相片
	 */
	@SuppressWarnings("unchecked")
	public List<Picture> queryPicture(Album album) throws Exception {
		try {
			album.getCondition().setDataCount(album.getTotal());
			album.setStatementName("queryPictureByPaging");
			List<Picture> pictures = pictureDao.selectByList(album);
			if (pictures.size() > 0) {
				for (Picture picture : pictures) {
					picture.setAlbum(album);
				}
			}
			return pictures;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查询相片
	 */
	@SuppressWarnings("unchecked")
	public List<Picture> queryPictureByAlbum(Album album) throws Exception {
		try {
			album.setStatementName("queryPictureByAlbum");
			List<Picture> pictures = pictureDao.selectByList(album);
			if (pictures.size() > 0) {
				for (Picture picture : pictures) {
					picture.setAlbum(album);
				}
			}
			return pictures;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 更新相片
	 */
	public Boolean updatePicture(Picture picture) throws Exception {
		try {
			// 把以前的picture查出来
			picture.setStatementName("findPicture");
			Picture oldPicture = (Picture) pictureDao.selectByObject(picture);
			// 更改数据
			picture.setStatementName("updatePicture");
			pictureDao.update(picture);
			// 如果相册改变了,就把相片移动到新相册里面
			if (!oldPicture.getAlbum().getId().equals(
					picture.getAlbum().getId())) {
				// 得到文件
				File oldfile = new File(Constant.ALBUM_PATH
						+ oldPicture.getUrl());
				File newfile = new File(Constant.ALBUM_PATH + picture.getUrl());
				FileInputStream fis = new FileInputStream(oldfile);
				FileOutputStream fos = new FileOutputStream(newfile);
				// 复制图片
				byte[] bytes = new byte[1024];
				while (fis.read(bytes) != -1) {
					fos.write(bytes);
				}
				// 删除原来的图片
				oldfile.delete();
			}
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 添加相册
	 */
	public Boolean addAlbum(Album album) throws Exception {
		try {
			String url = XgjWebUtils.getUUID();
			album.setStatementName("insertAlbum");
			album.setUrl(url);
			pictureDao.insert(album);
			// 创建目录
			File directory = new File(Constant.ALBUM_PATH + url);
			if (!directory.exists()) {
				if (!directory.mkdir()) {
					throw new RuntimeException("创建相册目录失败，检查。");
				}
			}
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 更改相册
	 */
	public Boolean updateAlbum(Album album) throws Exception {
		try {
			album.setStatementName("updateAlbum");
			pictureDao.update(album);
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 删除相册
	 */
	public Boolean deleteAlbum(Album album) throws Exception {
		try {
			album=findAlbum(album);
			album.setStatementName("deleteAlbum");
			pictureDao.delete(album);
			// 删除文件
			File directory = new File(Constant.ALBUM_PATH + album.getUrl());
			File[] files = directory.listFiles();
			for (File file : files) {
				file.delete();
			}
			// 删除相册目录
			directory.delete();
			return true;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 查找相册
	 */
	public Album findAlbum(Album album) throws Exception {
		try {
			album.setStatementName("findAlbum");
			album = (Album) pictureDao.selectByObject(album);
			return album;
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}

	}

	/**
	 * 查询相册
	 */
	public List<Album> queryAlbum() throws Exception {
		try {
			Album album = new Album();
			album.setStatementName("queryAlbum");
			return pictureDao.selectByList(album);
		} catch (RuntimeException e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}

	}

}
